<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use Dcat\Admin\Http\Controllers\AdminController;
use App\Models\Cabinet;
use Dcat\Admin\Layout\Content;
use Illuminate\Support\Facades\DB;
use Dcat\Admin\Admin;
use Dcat\Admin\Layout\Row;
use App\Admin\Actions\Form\DealUpload;
use Dcat\Admin\Widgets\Card;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class UploadToChartController extends Controller
{
    public function index(Content $content, $pid){
        //初始清空reids
        $redisKeyPrefix = md5(Admin::user()->id).'_';
        Redis::del($redisKeyPrefix.'legend');
        $keys = Redis::keys($redisKeyPrefix.'page_*');
        for ($i=1; $i <= count($keys); $i++) { 
            Redis::del($redisKeyPrefix.'page_'.$i);
        }
        return $content
            ->body(headmenu($pid, 8))
            ->body(new Card(new DealUpload()))
            ->body($this->showChart());
    }

    protected function showChart(){
        $sessionKey = md5(Admin::user()->id);
        $data['key'] = $sessionKey;
        return view('admin.cabinet.uploadChart', $data);
    }

    public function getUploadChart(Request $request){
        $param = $request->all();
        $page = $param['page'];
        $redisKeyPrefix = $param['key'].'_';
        
        if ($page == 1) {
            $legend = Redis::get($redisKeyPrefix.'legend');
            $series = Redis::get($redisKeyPrefix.'page_'.$page);
            if ($legend && $series) {
                $data['legend'] = json_decode($legend);
                $data['series'] = json_decode($series);
                Redis::del($redisKeyPrefix.'legend');
                Redis::del($redisKeyPrefix.'page_'.$page);
                return response()->json(['code'=>1, 'data' => $data, 'msg' => 'success']);
            }
        } else {
            $series = Redis::get($redisKeyPrefix.'page_'.$page);
            if ($series) {
                $data['series'] = json_decode($series);
                Redis::del($redisKeyPrefix.'page_'.$page);
                return response()->json(['code'=>1, 'data' => $data, 'msg' => 'success']);
            }
        }
        return response()->json(['code'=>0, 'msg' => 'no data']);
    }
}